<template>
  <div class="service-records-form">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑服务记录' : '添加服务记录' }}</h2>
    </div>

    <el-card class="form-card">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        style="max-width: 600px"
      >
        <el-form-item label="关联预约编号" prop="appointmentId">
          <el-input v-model.number="formData.appointmentId" placeholder="请输入关联预约编号" />
        </el-form-item>

        <el-form-item label="服务人员编号" prop="staffId">
          <el-input v-model.number="formData.staffId" placeholder="请输入服务人员编号" />
        </el-form-item>

        <el-form-item label="实际开始时间" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="选择实际开始时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="实际结束时间" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="选择实际结束时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="使用物品" prop="itemsUsed">
          <el-input
            v-model="formData.itemsUsed"
            type="textarea"
            :rows="3"
            placeholder="请输入使用物品/药品"
          />
        </el-form-item>

        <el-form-item label="服务详情" prop="serviceDetails">
          <el-input
            v-model="formData.serviceDetails"
            type="textarea"
            :rows="3"
            placeholder="请输入服务详情描述"
          />
        </el-form-item>

        <el-form-item label="费用明细" prop="costDetails">
          <el-input
            v-model="formData.costDetails"
            type="textarea"
            :rows="3"
            placeholder="请输入费用明细"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { serviceRecordsApi } from '@/api'
import type { ServiceRecords } from '@/types'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const formRef = ref<FormInstance>()

const formData = reactive<ServiceRecords>({
  recordId: undefined,
  appointmentId: 0,
  staffId: 0,
  startTime: '',
  endTime: '',
  itemsUsed: '',
  serviceDetails: '',
  costdetails: ''
})

// 表单验证规则
const formRules: FormRules = {
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  itemsUsed: [
    { required: true, message: '请输入使用的物品', trigger: 'blur' }
  ],
  serviceDetails: [
    { required: true, message: '请输入服务详情', trigger: 'blur' }
  ],
  costdetails: [
    { required: true, message: '请输入费用明细', trigger: 'blur' }
  ]
}

// 计算属性
const isEdit = computed(() => !!route.params.id)

// 获取服务记录详情
const fetchServiceRecordDetail = async (recordId: number) => {
  try {
    const response = await serviceRecordsApi.getById(recordId)
    if (response.code === 200) {
      Object.assign(formData, response.data)
    } else {
      ElMessage.error(response.message || '获取服务记录信息失败')
    }
  } catch (error) {
    console.error('获取服务记录详情失败:', error)
    ElMessage.error('获取服务记录信息失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    let response
    if (isEdit.value) {
      response = await serviceRecordsApi.update(formData)
    } else {
      response = await serviceRecordsApi.add(formData)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      router.push('/biz-manage/service-records')
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('提交失败，请检查网络或表单数据。')
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.push('/biz-manage/service-records')
}

// 初始化
onMounted(() => {
  if (isEdit.value) {
    const recordId = Number(route.params.id)
    if (recordId) {
      fetchServiceRecordDetail(recordId)
    }
  }
})
</script>

<style scoped>
.service-records-form {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-card {
  max-width: 800px;
  margin: 0 auto;
}
</style> 